import { BASE_URL } from "@/config";
import { clearStorage, throttle } from "@/utils/index.js";
// opts = {
// 	url,
// 	method,
// 	data,
// 	header,
// 	loader:{
// 		title:''
// 	},
// 	passCode
// }
export default function service(opts) {
  return new Promise((resolve, reject) => {
    const errorMsg = "服务器错误：";
    let defaultHeaders = {
      // "Content-Type": "application/x-www-form-urlencoded",
      "Content-Type": "application/json;charset=utf-8",
    };
    if (opts.header) {
      defaultHeaders = opts.header;
    }
    // console.log(opts, '>>>>')
    // 后台的防止重复提交
    if (opts.passCode) {
      // console.log(opts.passCode)
      defaultHeaders["passCode"] = opts.passCode;
    }
    // 开启遮罩层
    if (opts.loader) {
      uni.showLoading({
        title: opts.loader.title || "加载中",
      });
    }
    uni.request({
      url: BASE_URL + opts.url,
      method: opts.method,
      data: opts.data,
      header: defaultHeaders,
      success: (res) => {
        const result = res.data;
        const code = result.status || result.code;
        if (code === "000000") {
          resolve(result);
        } else if (code == 401 || code == 403) {
          throttle(() => {
            uni.showModal({
              title: "登录超时",
              content: "请重新登录",
              showCancel: false,
              confirmText: "重新登录",
              success: async (res) => {
                if (res.confirm) {
                  clearStorage();
                  uni.redirectTo({
                    url: "/pages/login/login",
                  });
                }
              },
            });
          }, 10000);
        } else {
          if (!opts.notTips) {
            const msg = result.mesg || result.message || result.error;
            console.log(BASE_URL + opts.url + "--1--");
            setTimeout(() => {
              uni.showToast({
                title: msg ? msg : errorMsg,
                icon: "none",
              });
            }, 10);
          }
          reject(result);
        }
      },
      fail: (err) => {
        // if (!opts.notTips) {
        const msg = err.mesg || err.message || err.error_description;
        uni.showToast({
          title: msg ? msg : errorMsg,
          icon: "none",
        });
        // }
        reject(err);
      },
      complete() {
        if (opts.loader) {
          uni.hideLoading();
        }
      },
    });
  });
}
